package org.example.projecttwo.common.utils;

import org.example.projecttwo.mapper.article.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class ArticleNoGenerator {

    private static ArticleMapper articleMapper;
    private static final Lock LOCK = new ReentrantLock();
    private static final String PREFIX = "ART";
    private static final int DIGITS = 3;

    @Autowired
    public void setArticleMapper(ArticleMapper mapper) {
        articleMapper = mapper;
    }

    /**
     * 生成格式为ART001、ART002的自增编号
     */
    public static String generateArticleNo() {
        LOCK.lock();
        try {
            // 查询当前最大文章编号
            String maxArticleNo = getMaxArticleNo();

            if (maxArticleNo == null) {
                // 没有记录时从001开始
                return PREFIX + String.format("%0" + DIGITS + "d", 1);
            }

            // 提取数字部分并加1
            int num = Integer.parseInt(maxArticleNo.substring(PREFIX.length()));
            num++;

            // 格式化为3位数字（自动补零）
            return PREFIX + String.format("%0" + DIGITS + "d", num);
        } finally {
            LOCK.unlock();
        }
    }

    /**
     * 获取最大文章编号（通过自定义SQL查询）
     */
    private static String getMaxArticleNo() {
        // 需要在ArticleMapper中添加对应的方法
        return articleMapper.selectMaxArticleNo();
    }
}